% The script is used to fill the IMF Ey and Ex data durinf
% the 2003 Halloween storm. OMNI data are not available during
% this time. Hence we use less reliable raw data from ACE

% load the orginal data used in the online calculator
load /data/backup/mnair/ace_tensor/acedata/ace_1995_2011.mat
fday = datenum(1995,1,1,0,0,0):5/1440:datenum(2011,12,31,23,59,30);

%load the raw data during Oct28-Nov4 from ACE raw data file sent by
%Mariangel
ndata = load('/home/mnair/projects/realtime_mag/swepam_mag_oct_28-nov_04_2003_V2.dat');
L = ndata == -9999.9;
ndata(L) = NaN;

%calculate fday
fdaynew = datenum(2003,0,0) + ndata(:,2) + 0.0316 ; % + 0.0316 is the time taken for the SW to reach
% the BOW shock's nose. Note that the original data are reduced to bow
% shock's nose, where as the new data is at L1 position. The cirrection number is
% obtained by plotting the two data together and finding their time difference

% calculate IEF Ey
ief_ey = -ndata(:,5).*ndata(:,13)./1000;

% calculate IEF Ex
ief_ex = -ndata(:,5).*ndata(:,12)./1000;


%interploate to OMNI time stamps


% need to start at  731882.0347222222 time stamp
L = fday > 731882.0347222222 & fday < datenum(2003,11,5,0,0,0);

ief_ey_int = interp1(fdaynew,ief_ey, fday(L));
ief_ex_int = interp1(fdaynew,ief_ex, fday(L));

% replace the data in the original vector
ace_all(L,3) = ief_ey_int;
ace_all(L,2) = ief_ex_int;


% save the data as short integer binary for GAE

% mutiply by 100

ief_ey_data = ace_all(:,3) * 100;
ief_ex_data = ace_all(:,2) * 100;
% turn all NaN to 9999

LL = isnan(ief_ey_data);
ief_ey_data(LL) = 9999;

LL = isnan(ief_ex_data);
ief_ex_data(LL) = 9999;


fid = fopen('/data/backup/mnair/ace_tensor/acedata/ace_1995_2011_Ey.bin','wb');
fwrite(fid,ief_ey_data,'int16');
fclose(fid);

fid = fopen('/data/backup/mnair/ace_tensor/acedata/ace_1995_2011_Ex.bin','wb');
fwrite(fid,ief_ex_data,'int16');
fclose(fid);



